package com.mall.order.mq.delay.producer;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.stereotype.Component;


import javax.annotation.PostConstruct;
import java.nio.charset.Charset;

@Slf4j
@Component
public class DelayOrderCancelProducer {

    private DefaultMQProducer producer;

    @PostConstruct
    public void init() {
        try {
            producer = new DefaultMQProducer("delay_order_cancel_producer");

            producer.setNamesrvAddr("127.0.0.1:9876");

            producer.start();
            log.info("DefaultMQProducer,启动！");
        } catch (MQClientException e) {
            e.printStackTrace();
        }

    }

    /*
           实现订单延迟消息的发送
     */
    public boolean sendDelayOrderCancelMessage(String orderId) {
        // 创建待发送的消息
        Message message = new Message();
        message.setTopic("delay_order_cancel");
        message.setBody(orderId.getBytes(Charset.forName("utf-8")));

        // 设置延迟消息的延迟，3
        // 非常简单
        // 延迟级别
        // 1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h
        // 1  2  3   4   5  6  7  8  9 10  11 12 13 14  15  16 17 18
        int delayTime = 4;
        message.setDelayTimeLevel(delayTime);
        log.info("DelayOrderCancelProducer，" + "设置延迟消息的延迟级别" + delayTime);

        SendResult sendResult = null;
        // 千万不要忘了添加日志信息，方便我们调试
        try {
            sendResult = producer.send(message);
        } catch (MQClientException e) {
            log.error("DelayOrderCancelProducer，" + e.getErrorMessage());
            e.printStackTrace();
        } catch (RemotingException e) {
            e.printStackTrace();
            log.error("DelayOrderCancelProducer，" + e.getMessage());
        } catch (MQBrokerException e) {
            e.printStackTrace();
            log.error("DelayOrderCancelProducer，" + e.getMessage());
        } catch (InterruptedException e) {
            e.printStackTrace();
            log.error("DelayOrderCancelProducer，" + e.getMessage());
        }

        if (sendResult != null && SendStatus.SEND_OK.equals(sendResult.getSendStatus())) {
            // 发送成功
            log.info("DelayOrderCancelProducer，" + "发送成功，orderId=" + orderId);
            return true;
        }
        log.info("DelayOrderCancelProducer，发送失败，orderId=" + orderId);
        // 消息发送失败
        return false;
    }
}
